package cn.net.springboot.netty.learn.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

/**
 * 自定义解码器
 *
 * @author Chris
 * @date 2019/05/20 15:58
 * @since 1.0.0
 */
// @ChannelHandler.Sharable
public class LuckDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 这里读取的顺序就是协议的顺序. 读取的次数与写的次数一定是一致的
        // | Version | Content-Length | SessionId | Content |

        // 获取协议的版本
        int version = in.readInt();
        // 获取消息长度
        int contentLength = in.readInt();
        // 获取SessionId
        byte[] sessionByte = new byte[36];
        in.readBytes(sessionByte);
        String sessionId = new String(sessionByte);

        // 组装协议头
        LuckHeader header = new LuckHeader(version, contentLength, sessionId);

        // 读取消息内容
        byte[] content = new byte[in.readableBytes()];
        in.readBytes(content);

        LuckMessage message = new LuckMessage(header, new String(content));

        out.add(message);
    }
}
